package com.liuc.practice.server.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @Author Liu Chang
 * @Date 2021/7/22 8:52 下午
 */
public class StaticResourceUtil {

    public static String getAbsolutePath(String path) {
//        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
          return "/Users/liuchang/webapps/" + path;

    }


    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {

        int resourceBytesCount = InputStreamUtil.getInputStreamBytesCount(inputStream);
        // 输出响应头信息
        outputStream.write(HttpProtocolResponseUtil.successHeader(resourceBytesCount).getBytes());

        // 将输入流 读取到 缓冲区 bytes[] 中，再从缓冲区中输出
        long written = 0; // 已经读取的内容长度
        int byteSize = 1024; // 由于读取内容可能过长，需要分批次缓冲
        byte[] bytes = new byte[byteSize];

        while (written < resourceBytesCount) {
            // 读取最后剩余一段缓冲内容（循环出口）
            if (written + byteSize > resourceBytesCount) {
                byteSize = (int)(resourceBytesCount - written);
                bytes = new byte[byteSize];
            }

            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();
            written += byteSize;
        }
    }
}
